/**
 * Copyright 2014,Peak Tai 台俊峰(taijunfeng_it@sina.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * 		http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.cenluan.kit;

import org.apache.commons.lang3.StringEscapeUtils;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;

import com.jfinal.plugin.activerecord.Model;

/**
 * 防xss攻击的工具类，具有转义字符串，过滤富文本相关方法
 * 
 * @author peak
 * 
 */
public class XssKit {
	/**
	 * 转义字符串
	 * 
	 * @param str
	 * @return
	 */
	public static String escapeStr(String str) {
		return StringEscapeUtils.escapeHtml4(str);
	}

	/**
	 * 转义字符串，返回结果长度不超过指定值
	 * 
	 * @param str
	 * @param maxLen
	 * @return
	 */
	public static String escapeStr(String str, int maxLen) {
		String s = StringEscapeUtils.escapeHtml4(str);
		if (s.length() > maxLen) {
			s = s.substring(0, maxLen);
		}
		return s;
	}

	/**
	 * 针对model的字段转义
	 * 
	 * @param model
	 * @param field
	 * @param maxLen
	 */
	@SuppressWarnings("rawtypes")
	public static void escape(Model model, String field, int maxLen) {
		String str = model.getStr(field);
		if (str == null) {
			return;
		}
		model.set(field, escapeStr(str, maxLen));
	}

	/**
	 * 过滤富文本，项目默认使用jsoup自带的白名单过滤，允许基本文本元素和图片，为了移动设备看起来更舒适一些
	 * 
	 * @param html
	 */
	public static String filterHtml(String html) {
		return Jsoup.clean(html, Whitelist.basicWithImages());
	}

	/**
	 * 对model的字段内容过滤富文本
	 * 
	 * @param model
	 * @param field
	 */
	@SuppressWarnings("rawtypes")
	public static void filterHtml(Model model, String field) {
		String value = model.getStr(field);
		model.set(field, filterHtml(value));
	}
}
